package com.design.boot.common.aop;

/**
 * @author kakayubei
 * @description
 * @date 2021/7/31 17:47
 */

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 日志切面
 */
@Component
@Aspect // 标注为切面
public class LogAspect {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    // 切入点表达式，表示切入点为控制器包中的所有方法
    @Pointcut("within(com.design.boot.controller.*)")
    public void logAspect() {
    }

    // 切入点之前执行
    @Before("logAspect()")
    public void doBefore(JoinPoint joinPoint) {
        logger.info("访问时间：{}--访问接口:{}", LocalDateTime.now(), joinPoint.getSignature());
    }

    @Around("logAspect()")
    public Object doAround(ProceedingJoinPoint joinPoint) {
        Object res = null;
        long start = System.currentTimeMillis();
        try {
            res = joinPoint.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        logger.info("访问接口:{} 访问耗时：{}", joinPoint.getSignature(), System.currentTimeMillis() - start);
        return res;
    }
}

